package com.jams.goodox.activity.mine.buy;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.czt.mp3recorder.MP3Recorder;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;
import com.jams.goodox.utils.Utils;
import com.shuyu.waveview.AudioPlayer;
import com.shuyu.waveview.AudioWaveView;
import com.shuyu.waveview.FileUtils;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/5/13.
 */

public class MineRecordActivity extends BaseActivity{

    @Bind(R.id.audioWave)
    AudioWaveView audioWave;
    @Bind(R.id.record)
    TextView record;
    //ImageView record;
    @Bind(R.id.stop)
    TextView stop;

    @Bind(R.id.play)
    TextView play;
    //ImageView play;


    @Bind(R.id.reset)
    TextView reset;
    //    @Bind(R.id.playText)
//    TextView playText;
    @Bind(R.id.colorImg)
    ImageView colorImg;
    @Bind(R.id.recordPause)
    TextView recordPause;
    @Bind(R.id.rootView)
    ViewGroup rootView;
    @Bind(R.id.tx_time)
    TextView tx_time;
    @Bind(R.id.edit)
    EditText edit;

    @Bind(R.id.media_record)
    ImageView media_record;
    @Bind(R.id.media_play)
    ImageView media_play;

    MP3Recorder mRecorder;
    AudioPlayer audioPlayer;

    String filePath;


    boolean mIsRecord = false;

    boolean mIsPlay = false;

    int duration;
    int curPosition;
    private Disposable disposable;

    @Override
    protected int getLayoutId() {
        return R.layout.mine_record_activity;
    }

    @Override
    protected void init() {
        resolveNormalUI();
        titleBar.setBackgroundColor(getResources().getColor(R.color.font_color_deep_gray));
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.font_color_deep_gray));//沉侵式头部
        StyleUtil.titleBackKeyWithRightTextViewListener(this, "课程录制", "下一步", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
                    Toast.makeText(MineRecordActivity.this, "文件不存在", Toast.LENGTH_SHORT).show();
                    return;
                }
                String title=edit.getText().toString();
                if(TextUtils.isEmpty(title)){
                    Toast.makeText(MineRecordActivity.this, "标题不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                Bundle bundle=new Bundle();
                bundle.putString("filePath",filePath);
                bundle.putString("title",title);
                bundle.putInt("time",time);
                //qStartActivityForResult(RecordNextStepActivity.class,bundle,101);
                qStartActivity(RecordFirstStepActivity.class,bundle);
            }
        });
        initPlayer();
    }

    private void initPlayer(){
        if(audioPlayer==null)
        audioPlayer = new AudioPlayer(this, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case AudioPlayer.HANDLER_CUR_TIME://更新的时间
                        curPosition = (int) msg.obj;
                        tx_time.setText(toTime(curPosition) + " / " + toTime(duration));
                        break;
                    case AudioPlayer.HANDLER_COMPLETE://播放结束
//                        tx_time.setText(" ");
                        mIsPlay = false;
                        media_play.setImageResource(R.mipmap.shiting_zhengchang);
                        break;
                    case AudioPlayer.HANDLER_PREPARED://播放开始
                        duration = (int) msg.obj;
                        tx_time.setText(toTime(curPosition) + " / " + toTime(duration));
                        media_play.setImageResource(R.mipmap.shiting_anxia);
                        media_record.setImageResource(R.mipmap.luyin_zhengchang);
                        break;
                    case AudioPlayer.HANDLER_ERROR://播放错误
                        resolveResetPlay();
                        media_play.setImageResource(R.mipmap.shiting_zhengchang);
                        break;
                }

            }
        });
    }


    @Override
    protected void onRestart() {
        super.onRestart();
        initPlayer();
    }

    private int time=0;
    static final int MAX_TIME=30*60;
    private void doDelay(){
        if(disposable==null||disposable.isDisposed())
        disposable=Observable.interval(0,1000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.single())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if(++time>MAX_TIME){
                            if (disposable!=null) disposable.dispose();
                            resolveStopRecord();
                            return;
                        }
                        tx_time.setText(getFormatData(time));
                    }
                });

    }

    private String getFormatData(int time){
        if(time<=0)return "00:00";
        else {
            String a=(time/60)>9?String.valueOf(time/60):"0"+time/60;
            String b=(time%60)>9?String.valueOf(time%60):"0"+time%60;
            return a+":"+b;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mIsRecord) {
            destroDis();
            resolveStopRecord();

            media_record.setImageResource(R.mipmap.luyin_zhengchang);

            //resolveStopRecord();
        }
        if (mIsPlay) {
            audioPlayer.pause();
            //audioPlayer.stop();

            media_play.setImageResource(R.mipmap.shiting_zhengchang);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

//        try {
//            mRecorder.stop();
//            audioPlayer.stop();
//        }catch (Exception e){
//
//        }

    }

    @OnClick({R.id.record, R.id.stop, R.id.play, R.id.reset, R.id.recordPause,R.id.media_record,R.id.media_play})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.record:
                AndPermission.with(this)
                        .requestCode(101)
                        .callback(this)
                        .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO)
                        .start();
                break;
            case R.id.stop:
                destroDis();
                resolveStopRecord();
                break;
            case R.id.play:
                destroDis();
                resolvePlayRecord();
                break;
            case R.id.reset:
                destroDis();
                resolveResetPlay();
            case R.id.recordPause:
                resolvePause();
//                destroDis();
                break;

            case R.id.media_record:
                if (mIsPlay) {
                    audioPlayer.pause();
                    //audioPlayer.stop();
                    mIsPlay = false;
                    media_play.setImageResource(R.mipmap.shiting_zhengchang);
                }

                if(mIsRecord){
                    destroDis();
                    resolveStopRecord();
                    media_record.setImageResource(R.mipmap.luyin_zhengchang);
                }else {
                    AndPermission.with(this)
                            .requestCode(101)
                            .callback(this)
                            .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO)
                            .start();

                    media_record.setImageResource(R.mipmap.luyin_anxia);
                }

                break;

            case R.id.media_play:

                if (mIsRecord) {
                    destroDis();
                    resolveStopRecord();
                    media_record.setImageResource(R.mipmap.luyin_zhengchang);
                }

                if (mIsPlay) {
                    mIsPlay = false;
                    audioPlayer.pause();
                    //audioPlayer.stop();
                    resetTime();

                    media_play.setImageResource(R.mipmap.shiting_zhengchang);
                }else {
                    destroDis();
                    resolvePlayRecord();
                }

                break;

                default:
                    break;
        }
    }

    private void resetTime(){
        time=0;
        tx_time.setText("00:00");
    }

    @PermissionYes(101)
    private void externalPermissionIsOk(List<String> grantedPermissions){
        destroDis();
        resolveRecord();
    }
    @PermissionNo(101)
    private void externalPermissionIsNo(List<String> grantedPermissions){
        ToastUtil.show(this,"获取存储权限or麦克风权限失败");
    }

    private void destroDis(){
        if(disposable!=null&&!disposable.isDisposed()){
            disposable.dispose();
            disposable=null;
        }
    }

    /**
     * 开始录音
     */
    private void resolveRecord() {
        filePath = FileUtils.getAppPath();
        File file = new File(filePath);
        if (!file.exists()) {
            if (!file.mkdirs()) {
                Toast.makeText(this, "创建文件失败", Toast.LENGTH_SHORT).show();
                return;
            }
        }

        int offset = Utils.dp2px(this,1);
        filePath = FileUtils.getAppPath()  + ".mp3";
        mRecorder = new MP3Recorder(new File(filePath));
        int size = getScreenWidth(this) / offset;//控件默认的间隔是1
        mRecorder.setDataList(audioWave.getRecList(), size);

        mRecorder.setErrorHandler(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == MP3Recorder.ERROR_TYPE) {
                    Toast.makeText(MineRecordActivity.this, "没有麦克风权限", Toast.LENGTH_SHORT).show();
                    resolveError();
                    media_record.setImageResource(R.mipmap.luyin_zhengchang);
                }
            }
        });

        //audioWave.setBaseRecorder(mRecorder);

        try {
            mRecorder.start();
            audioWave.startView();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "录音出现异常", Toast.LENGTH_SHORT).show();
            resolveError();
            return;
        }
        resolveRecordUI();
        time=0;
        tx_time.setText("00:00");
        doDelay();
        mIsRecord = true;

    }

    /**
     * 停止录音
     */
    private void resolveStopRecord() {
        resolveStopUI();
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.setPause(false);
            mRecorder.stop();
            audioWave.stopView();
        }
        mIsRecord = false;
        recordPause.setText("暂停");

    }

    /**
     * 录音异常
     */
    private void resolveError() {
        resolveNormalUI();
        FileUtils.deleteFile(filePath);
        filePath = "";
        if (mRecorder != null && mRecorder.isRecording()) {
            mRecorder.stop();
            audioWave.stopView();
        }

    }

    /**
     * 播放
     */
    private void resolvePlayRecord() {
        if (TextUtils.isEmpty(filePath) || !new File(filePath).exists()) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        tx_time.setText("00:00");
        mIsPlay = true;
//        time=0;
//        tx_time.setText("00:00");
//        doDelay();

        audioPlayer.playUrl(filePath);

        resolvePlayUI();
    }

    /**
     * 播放
     */
    private void resolvePlayWaveRecord() {
    }

    /**
     * 重置
     */
    private void resolveResetPlay() {
        filePath = "";
        resetTime();
        if (mIsPlay) {
            mIsPlay = false;
            audioPlayer.pause();
        }
        resolveNormalUI();
    }

    /**
     * 暂停
     */
    private void resolvePause() {
        if (!mIsRecord)
            return;
        resolvePauseUI();
        if (mRecorder.isPause()) {
            resolveRecordUI();
            doDelay();
            audioWave.setPause(false);
            mRecorder.setPause(false);
            recordPause.setText("暂停");
            doDelay();

        } else {
            audioWave.setPause(true);
            mRecorder.setPause(true);
            recordPause.setText("继续");
            destroDis();
        }
    }

    private String toTime(long time) {
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        String dateString = formatter.format(time);
        return dateString;
    }

    private void resolveNormalUI() {
        record.setEnabled(true);
        recordPause.setEnabled(false);
        stop.setEnabled(false);
        play.setEnabled(false);
        reset.setEnabled(false);

    }

    private void resolveRecordUI() {
        record.setEnabled(false);
        recordPause.setEnabled(true);
        stop.setEnabled(true);
        play.setEnabled(false);
        reset.setEnabled(false);

    }

    private void resolveStopUI() {
        record.setEnabled(true);
        stop.setEnabled(false);
        recordPause.setEnabled(false);
        play.setEnabled(true);
        reset.setEnabled(true);

    }

    private void resolvePlayUI() {
        record.setEnabled(false);
        stop.setEnabled(false);
        recordPause.setEnabled(false);
        play.setEnabled(true);
        reset.setEnabled(true);

    }

    private void resolvePauseUI() {
        record.setEnabled(false);
        recordPause.setEnabled(true);
        stop.setEnabled(false);
        play.setEnabled(false);
        reset.setEnabled(false);

    }


    /**
     * 获取屏幕的宽度px
     *
     * @param context 上下文
     * @return 屏幕宽px
     */
    public static int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();// 创建了一张白纸
        windowManager.getDefaultDisplay().getMetrics(outMetrics);// 给白纸设置宽高
        return outMetrics.widthPixels;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            setResult(RESULT_OK);
            finish();
        }
    }
}
